package game.leon.engine.net.codec;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolEncoderAdapter;
import org.apache.mina.filter.codec.ProtocolEncoderOutput;

/**
 * User: bianpeng
 * Date: 11-12-27
 */
class GateProtocolEncoder extends ProtocolEncoderAdapter {
    @Override
    public void encode(IoSession session, Object message, ProtocolEncoderOutput out) throws Exception {
        GateRawMessage rawMessage = (GateRawMessage) message;
        assert rawMessage != null;
        IoBuffer buffer = IoBuffer.allocate(
                rawMessage.getData().length + GateProtocolDecoder.BUFFER_PREFIX_LENGTH + 2,
                false);
        // 这里是实际数据长度, 8字节的PREFIX长度, 不包含在内
        int dataLen = rawMessage.getData().length + 2;
        buffer.putUnsignedShort(dataLen); // 2, data length
        buffer.putUnsignedInt(rawMessage.getUserId()); // 4, useId
        buffer.putUnsignedShort(rawMessage.getMessage()); // 2, message
        buffer.put(rawMessage.getData());
        buffer.flip();
        out.write(buffer);
    }
}
